package cn.cheqi.recovery.background.controller;


import cn.cheqi.recovery.background.dto.DataGridView;
import cn.cheqi.recovery.background.dto.ResultDTO;
import cn.cheqi.recovery.background.entity.Employee;
import cn.cheqi.recovery.background.mapper.EmployeeMapper;
import cn.cheqi.recovery.background.service.EmployeeService;
import cn.cheqi.recovery.background.utils.SysFileUtils;
import cn.cheqi.recovery.background.vo.EmployeeVO;
import cn.cheqi.recovery.background.vo.OrderVO;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  员工前端控制器
 * </p>
 *
 * @author Robin
 * @since 2020-02-23
 */
@RestController
@RequestMapping("/system/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 加载所有员工信息
     * @param employeeVO
     * @return
     */
    @RequestMapping("/loadAllEmployees")
    public DataGridView loadAllEmployees(EmployeeVO employeeVO){
        IPage<Employee> page = new Page<>(employeeVO.getPage(),employeeVO.getLimit());
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        //获取模糊查询的条件
        //员工编号
        Long empId = employeeVO.getEmpId();
        //员工姓名
        String empName = employeeVO.getEmpName();
        //员工联系方式
        String empPhone = employeeVO.getEmpPhone();
        //清除模糊查询三个条件里的空格
        if (empId != null){
            wrapper.like("emp_id",empId);
        }
        if (!StringUtils.isBlank(empName)){
            String newEmpName = empName.replace(" ", "");
            wrapper.like(newEmpName != null,"emp_name",newEmpName);
        }
        if (!StringUtils.isBlank(empPhone)){
            String newEmpPhone = empPhone.replace(" ", "");
            wrapper.like(newEmpPhone != null, "emp_phone",empPhone);
        }
        wrapper.orderByDesc("emp_id");
        employeeService.page(page,wrapper);
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    /**
     * 通过员工ID查出员工详情,通过员工ID多表联查查出员工所属小区
     * @param employeeVO
     * @return
     */
    @RequestMapping("/detailEmpById")
    public EmployeeVO detailEmpById(EmployeeVO employeeVO){
        EmployeeVO empVO = employeeMapper.findEmpDetailById(employeeVO.getEmpId());
        //System.out.println(empVO);
        return empVO;
    }

    /**
     * 添加员工
     * @param employeeVO
     * @return
     */
    @PostMapping("/addEmployee")
    @Transactional
    public ResultDTO addEmployee(EmployeeVO employeeVO){
        try {
            //判断employeeVO中的图片后缀是否以_temp结束
            //如果是,去掉后缀并保存
            if(employeeVO.getEmpPic()!=null && employeeVO.getEmpPic().endsWith("_temp")){
                //去除多余后缀后的名字
                String saveName = SysFileUtils.reNameFile(employeeVO.getEmpPic());
                employeeVO.setEmpPic(saveName);
            }
            employeeService.save(employeeVO);
            return new ResultDTO(200,"添加成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ResultDTO(-1,"添加失败");
        }
    }

    /**
     * 通过员工ID编辑员工信息
     * @param employeeVO
     * @return
     */
    @PostMapping("/editEmployee")
    @Transactional
    public ResultDTO editEmployeeById(EmployeeVO employeeVO){
        try {
            //判断是否为默认图片
            if (!(employeeVO.getEmpPic()!=null && employeeVO.getEmpPic().endsWith(SysFileUtils.Default_Img_Path))){
                //判断userVO中的图片后缀是否以_temp结束
                //如果是,去掉后缀并保存
                if(employeeVO.getEmpPic().endsWith("_temp")){
                    //去除多余后缀后的名字
                    String saveName = SysFileUtils.reNameFile(employeeVO.getEmpPic());
                    employeeVO.setEmpPic(saveName);
                    //判断是否为默认图片,如果不是则删除原来的图片
                    String oldPath = employeeService.getById(employeeVO.getEmpId()).getEmpPic();
                    if (!oldPath.equals(SysFileUtils.Default_Img_Path)){
                        SysFileUtils.removeOldFile(oldPath);
                    }
                }
            }
            employeeService.updateById(employeeVO);
            return new ResultDTO(200,"修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO(-1,"修改失败");
        }
    }

    /**
     * 通过员工ID删除员工
     * @param employeeVO
     * @return
     */
    @PostMapping("/deleteEmpById")
    @Transactional
    public ResultDTO deleteEmployeeById(EmployeeVO employeeVO){
        try {
            //判断用户的头像图片是否为默认图片,若不是则删除
            Long empId = employeeVO.getEmpId();
            String avatarUrl = employeeService.getById(empId).getEmpPic();
            if (!avatarUrl.equals(SysFileUtils.Default_Img_Path)){
                SysFileUtils.removeOldFile(avatarUrl);
            }
            employeeService.removeById(employeeVO.getEmpId());
            return new ResultDTO(200,"删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO(-1,"删除失败");
        }
    }

    /**
     * 用户头像上传
     * @param multipartFile
     * @return
     */
    @RequestMapping("/file/uploadEmpPic")
    public Map<String,Object> uploadUserImg(@RequestParam("file") MultipartFile multipartFile){
        //1.得到文件的老名字
        String oldFileName = multipartFile.getOriginalFilename();
        //2.根据文件名生成新的文件名
        String newName = SysFileUtils.createNewFileName(oldFileName);
        //3.得到当前日期的字符串
        String dirName = DateUtil.format(new Date(),"yyyy-MM-dd");
        //构造员工存储的文件夹
        String empSave = SysFileUtils.Emp_Save_Folder + dirName;
        //4.构造文件夹
        File dirFile = new File(SysFileUtils.UPLOAD_PATH,empSave);
        //5.判断当前文件夹是否存在
        if (!dirFile.exists()){
            //如果不存在则创建这个文件夹
            dirFile.mkdirs();
        }
        //6.构造文件对象
        File file = new File(dirFile, newName+"_temp");
        //7.把mf里面的图片信息写入file
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String,Object> map = new HashMap<String, Object>();
        //8.返回图片的相对路径
        map.put("path",empSave+"/"+newName+"_temp");
        return map;
    }

    /**
     * 员工头像下载
     * @param path
     * @return
     */
    @RequestMapping("/file/showImgByPath")
    public ResponseEntity<Object> showImgByPath(String path){
        return SysFileUtils.createResponseEntity(path);
    }

    /**
     * 通过员工ID查出该员工的所有订单详情
     * @param employeeVO
     * @return
     */
    @PostMapping("/findOrdersByEmpId")
    public DataGridView findOrdersByEmpId(EmployeeVO employeeVO){
        //分页条件
        Page<Employee> page = new Page<>();
        if (employeeVO.getPage() != null && employeeVO.getLimit() != null){
            page.setPages(employeeVO.getPage());
            page.setSize(employeeVO.getLimit());
        }
        List<OrderVO> orderVOS = employeeMapper.findOrdersByEmpId(employeeVO.getEmpId(),page);
        return new DataGridView(page.getTotal(),orderVOS);
    }
}

